"""
群聊聊天室客户端
"""
from socket import *
from multiprocessing import *

# 服务端地址
ADDR = ("127.0.0.1", 8888)


def login(sock):
    while True:
        name = input("请输入昵称：")
        if len(name) < 3 or " " in name:
            continue
            # 发送请求
        msg = "LOGIN " + name
        sock.sendto(msg.encode(), ADDR)
        # 等待结果 b"OK"  b"FAIL"
        result, addr = sock.recvfrom(128)
        if result == b"OK":
            print("您已进入聊天室")
            return name
        else:
            print("该昵称已存在")


def recv_msg(sock):
    while True:
        data, addr = sock.recvfrom(1024 * 1024)
        print("\n" + data.decode() + "\n发言：", end="")


def send_msg(sock, name):
    while True:
        try:
            content = input("发言：")
            if not content:
                continue  # 不允许输入为空
        except KeyboardInterrupt:
            break
        if content == "exit":
            break
        msg = "CHAT %s %s" % (name, content)
        sock.sendto(msg.encode(), ADDR)


def exit(sock, name):
    msg = "EXIT " + name
    sock.sendto(msg.encode(), ADDR)
    print("您已退出群聊")


def main():
    sock = socket(AF_INET, SOCK_DGRAM)
    sock.bind(("0.0.0.0", 8829))
    name = login(sock)  # 进入聊天室
    p = Process(target=recv_msg, args=(sock,), daemon=True)
    p.start()
    send_msg(sock, name)
    exit(sock, name)


if __name__ == '__main__':
    main()
